<?php

namespace App\Api\Traits\Orm;

trait ScopeTrait
{
    /**
     * @exp 多条件模糊查询
     * @param $query
     * @param array $search_params 模糊查询的字段
     * @param $search_val 查询的值
     * @return bool
     */
    public function scopeLikeSearch($query, array $search_params, $search_val)
    {
        return $query->where(function ($query) use ($search_params, $search_val) {
            foreach ($search_params as $search_param) {
                $query->orWhere($search_param, 'like', "%$search_val%");
            }
        });
    }


    /**
     * 关联查询只查询指定字段
     * @param $query
     * @param $relation
     * @param array $columns
     * @return mixed
     */
    public function scopeWithOnly($query, $relation, array $columns)
    {
        return $query->with([$relation => function ($query) use ($columns) {
            $query->select(array_merge(['id'], $columns));
        }]);
    }
}
